/*
 * @Description:
 * @Author: chenjiaxin
 * @Date: 2022-07-17 20:45:01
 * @LastEditTime: 2022-07-19 22:33:43
 * @FilePath: \rollup-plugin-compression\src\index.ts
 */
// const { cwd } = require("node:process");
// const path = require("path");
// const compressing = require("compressing");
// const chalk = require("chalk");

import { cwd } from "node:process";
import path from "path";
import compressing from "compressing";
import fs from "fs";
// import chalk from "chalk";

export interface ICompressionOptions {
  sourceName: string;
  type?: "zip" | "tar";
  targetName?: string;
  ignoreBase?: boolean;
}

const defaultOption: ICompressionOptions = {
  sourceName: "dist",
  type: "zip",
  targetName: "dist",
  ignoreBase: false //默认打包源文件夹本身,配置为true则只打包文件夹内文件
};

// 删除 目录 及 目录中的所有 目录和文件
const deleteDir = (targetPath: string) => {
  // 1. 判断 路径是否存在
  if (!fs.existsSync(targetPath)) return;
  // 2. 获取该路径下所有目录名和文件名
  const files = fs.readdirSync(targetPath);
  files.forEach((file) => {
    // 3. 拼接 目录下的目录路径 和 文件路径
    const curPath = path.resolve(targetPath, file);
    // 4. 判断是否 是目录
    if (fs.statSync(curPath).isDirectory()) {
      // 是目录  递归删除里面的 文件
      deleteDir(curPath);
    } else {
      // 是文件 删除
      fs.unlinkSync(curPath);
    }
  });
  // 删除 目录
  fs.rmdirSync(targetPath);
};

const deleteDirFile = (targetPath: string, buildType: string) => {
  const rootPathFiles = fs.readdirSync(targetPath);
  // console.log("获取==根路径下文件", rootPathFiles);
  rootPathFiles.forEach((file) => {
    const currentPath = path.resolve(targetPath, file);
    // 判断是否是目录
    if (!fs.statSync(currentPath).isDirectory()) {
      // 不是目录 说明是文件
      // 获取文件扩展名
      const extname = path.extname(file);
      if (extname === `.${buildType}`) {
        // 判断是否 是 打包的文件  是 就删除文件
        fs.unlinkSync(currentPath);
      }
    }

    // console.log("根路劲下目录和文件", currentPath);
  });
};

const compressionBuild = (options: ICompressionOptions = defaultOption) => {
  // const { sourceName, targetName = "dist" } = options;
  const sourceName = options.sourceName ?? "dist";
  const type = options.type ?? "zip";
  const targetName = options.targetName ?? "dist";
  const rootPath = cwd();
  const buildPath = path.resolve(rootPath, sourceName);
  return {
    name: "compression",
    buildStart() {
      //1. 删除 build 构建目录
      deleteDir(buildPath);

      //2. 删除 目录下 指定的扩展名 文件
      deleteDirFile(rootPath, type);
    },
    closeBundle() {
      console.log("closeBundle");
      compressing.zip
        .compressDir(buildPath, `${targetName}.${type}`, { ignoreBase: options.ignoreBase ?? false })
        .then((res: any) => {
          console.log("compress completed ~");
          // console.log(chalk.cyan(`compress-${sourceName}:  ${sourceName} compress completed!`));
        })
        .catch((err: any) => {
          // console.log(chalk.cyan(`compress error ~`));
        });
    }
  };
};
export default compressionBuild;
